﻿using Ly.EBussiness.Auth;
using Ly.EBussiness.Core;
using Ly.EBussiness.EntityFrameworkCore.Auth;
using Ly.EBussiness.EntityFrameworkCore.Auth.User;
using Ly.EBussiness.Filter;
using Ly.EBussiness.Filter.WrapResult;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Modularity;

namespace Ly.EBussiness;

[DependsOn(typeof(AbpAspNetCoreMvcModule), typeof(CoreModule))]
public class EBussinessModule : AbpModule
{
    public override Task PreConfigureServicesAsync(ServiceConfigurationContext context)
    {
        context.Services.AddSwaggerGen();
        return base.PreConfigureServicesAsync(context);
    }

    public override void OnApplicationInitialization(ApplicationInitializationContext context)
    {
        var app = context.GetApplicationBuilder();
        var env = context.GetEnvironment();
        // Configure the HTTP request pipeline.
        if (env.IsDevelopment())
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
            app.UseSwagger();
            app.UseSwaggerUI();
        }


        // app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();


        app.UseConfiguredEndpoints();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public override void PreConfigureServices(ServiceConfigurationContext context)
    {
        // 设置验证方式为 Bearer Token
        // 添加 using Microsoft.AspNetCore.Authentication.JwtBearer;
        // 你也可以使用 字符串 "Brearer" 代替 JwtBearerDefaults.AuthenticationScheme
        context.Services.AddSingleton<IAuthorizationHandler, AuthPolicyHandler>();
        context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = JwtHelp.CreateTokenValidationParameters();
            });

        //验证权限
        context.Services.AddAuthorizationBuilder()
            .AddPolicy(PolicyName.DEFAULT, policy => { policy.Requirements.Add(new HasAllRolesRequirement(Role.CustomUser, Role.Admin)); })
            .AddPolicy(PolicyName.ADMIN, policy => { policy.Requirements.Add(new HasAllRolesRequirement(Role.Admin)); })
            .AddPolicy(PolicyName.COMMON, policy => { policy.Requirements.Add(new HasAllRolesRequirement(Role.CustomUser)); });
        
        //统一返回值
        context.Services.AddMvc(options =>
        {
            // options.Filters.Add(typeof(WrapResultAttribute),-1);
            options.Filters.Add(typeof(ResultFilter));
        });
        
        
        base.PreConfigureServices(context);
    }
}